﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Resources;

namespace Icms.WebUI.Controllers
{
    public class CourtAjaxDropdownController : Controller
    {
        private readonly IRepo<Court> courtRepo;
        private readonly IRepo<CourtType> courtTypeRepo;

        public CourtAjaxDropdownController(IRepo<Court> courtRepo, IRepo<CourtType> courtTypeRepo)
        {
            this.courtRepo = courtRepo;
            this.courtTypeRepo = courtTypeRepo;
        }

        public ActionResult GetItems(Guid? key, Guid? parent, Guid? self)
        {
            var list = new List<SelectListItem> { new SelectListItem { Text = Mui.not_selected, Value = "" } };

            IEnumerable<Court> result;

            if (parent.HasValue)
            {
                var c = courtTypeRepo.Get(parent.Value).Code;
                result = courtRepo.Where(o => o.CourtType.Code == c + 1);
                if (self.HasValue) result = result.Where(o => o.Id != self.Value);
            }
            else
            {
                result = courtRepo.GetAll().Where(c => !c.IsAdministrative).OrderBy(c => c.Title);
            }

            list.AddRange(result.Select(o => new SelectListItem
                                               {
                                                   Text = o.Title,
                                                   Value = o.Id.ToString(),
                                                   Selected = false
                                               }));
            return Json(list);
        }
    }
}